package com.far.permisions.rule;

import cn.hutool.core.bean.BeanUtil;
import com.far.permisions.tools.YamlTools;
import com.far.permissions.rule.RuleConfigProvider;
import com.far.permissions.bean.persistence.TableRule;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

public class YamlRuleConfigProvider implements RuleConfigProvider {
    private final String yamlPath;

    private List<TableRule> cache;

    public YamlRuleConfigProvider(String yamlPath) {
        this.yamlPath = yamlPath;
    }

    @Override
    public TableRule getRulesByTable(String table) {
        List<TableRule> allRules = getAllRules();
        return allRules.stream().filter(tableRule -> table.equals(tableRule.getTable())).findFirst().orElse(null);
    }

    @Override
    public List<TableRule> getRulesByTables(Set<String> tables) {
        List<TableRule> allRules = getAllRules();
        return allRules.stream().filter(tableRule -> tables.contains(tableRule.getTable())).collect(Collectors.toList());
    }

    @Override
    public List<TableRule> getAllRules() {
        if (cache != null) {
            return cache;
        }

        Map<String, Object> map = YamlTools.loadYaml(yamlPath);
        List<TableRule> tableRules = BeanUtil.copyToList((Collection<?>) map.get("tableRules"), TableRule.class);
        setCache(tableRules);
        return tableRules;
    }

    private synchronized void setCache(List<TableRule> newCache) {
        this.cache = newCache;
    }
}
